/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 */

import fs from 'fs';
import os from 'os';
import path from 'path';

import { HvigorLogger } from '../log/hvigor-log.js';

export class JsonReader {
  private static logger: HvigorLogger = HvigorLogger.getLogger(JsonReader.name);

  public static getJsonText(jsonPath: string, encodingStr = 'utf-8'): string {
    return fs.readFileSync(path.resolve(jsonPath), { encoding: encodingStr as BufferEncoding });
  }

  /**
   * 获取json对象
   *
   * @param {string} jsonPath json路径
   * @param {any} encodingStr 编码方式
   */
  public static getJsonObj(jsonPath: string, encodingStr = 'utf-8'): any {
    const text = fs.readFileSync(path.resolve(jsonPath), { encoding: encodingStr as BufferEncoding });

    try {
      return JSON.parse(text);
    } catch (e) {
      if (e instanceof SyntaxError) {
        const msg = e.message.split('at ');
        if (msg.length === 2) {
          JsonReader.logger.printErrorExit('JSON_READER_SYNTAX_ERROR', [msg[0].trim(), jsonPath, msg[1].trim()]);
        }
      }
      JsonReader.logger.printErrorExit('NOT_CORRECT_JSON_FORMAT', [jsonPath]);
    }
  }

  /**
   * 解析字符串为对象expected
   *
   * @param text 解析字符串
   * @param expected 期望返回对象类型实例, 也作为failsafe返回
   * @param reviver 自定义解析规则
   */
  public static parseJsonText<T>(text: string, expected?: T, reviver?: (this: any, key: string, value: any) => any): T {
    let obj;
    try {
      obj = JSON.parse(text, reviver);
    } catch (e) {
      obj = expected;
      JsonReader.logger.warn(`Failed to parse the JSON text '${text}'.`);
    }
    return obj;
  }
}
